import { Base64 } from './base64.js'
import { util } from './crypto.js'
import { HMAC } from './hmac.js'
import { SHA1 } from './sha1.js'

// 下面这3个信息必填
const url = 'https://zyprod.oss-cn-shenzhen.aliyuncs.com/'
const OSSAccessKeyId = 'LTAI5tLRaaRm8XhkNZj1kSgq'
const OssAccesskeySercet= 'RBPqGhSkEHMdyDVqelryXezJRQHiWn';


const policyText = {
  "expiration": "2034-01-01T12:00:00.000Z", // 设置Policy的有效期，格式为UTC时间。如果Policy失效，将无法上传文件。
  "conditions": [
  ["content-length-range", 0, 1048576000] // 限制上传文件的大小，单位为字节，此处限制文件大小为1 GB。如果上传的文件大小超过此限制，文件将无法上传到OSS。如果未设置该限制，则默认文件大小最大为5 GB。
  ]
}

const policy = Base64.encode(JSON.stringify(policyText))
const bytes = HMAC(SHA1, policy, OssAccesskeySercet, { asBytes: true })
const signature = util.bytesToBase64(bytes)

// 生成文件名随机字符串
const random_string = ()=>{
	return new Date().getTime() + "";
}

// 获取文件后缀
const get_suffix = (filename)=> {
    const pos = filename.lastIndexOf('.')
    let suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

// 获取文件后缀
const getFileName = (file)=>{
	  const fileName = random_string(10) + get_suffix(file)
    // // #ifdef APP
    // fileName = "android_" + random_string(10) + get_suffix(file)
    // // #endif
    // // #ifdef APP-IOS
    // fileName = "ios_" + random_string(10) + get_suffix(file)
    // // #endif
    return fileName;
}

export const uploadOSS = (dir, filePath) => {
  const name = getFileName(filePath);
  const key = dir + "/"+uni.getStorageSync('userId')+ "/" +name;
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url,
      filePath,
      name: 'file',
      formData: {
        name,
        key,
        policy,
        OSSAccessKeyId,
        success_action_status: '200',
        signature
      },
      success: () => {
        resolve({success: true, picUrl: url + key, fileName: name})
      },
      fail: (err) => {
		  console.log("oss上传失败: " + JSON.stringify(err));
          reject({success: false, data: '上传失败'})
		  uni.$toast.showToast('oss上传失败')
      }
    })
  })
} 